/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package imagefilter;


import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;

import java.io.*;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;

import com.drew.metadata.*;
import com.drew.metadata.iptc.*;


/**
 *
 * @author gioak
 */
public class ImageFilter {

    public static void main(String[] args) 
    {

         String path = args[0];
         String filename = args[1];
         String command = args[2];
         try {
         //Solr cell can also index MS file (2003 version and 2007 version) types.

         System.out.println(path);
         //this will be unique Id used by Solr to index the file contents.
         InetAddress ip = InetAddress.getByName("127.0.0.1");
         String hostname = ip.getHostName();
         String solrId = hostname + "|" + path;

       if(command.equals("INSERT"))
       {
            indexFilesSolrCell(path, filename, solrId);
       }
       else if(command.equals("UPDATE"))
       {

       }
       else if(command.equals("DELETE"))
       {
            deleteFilesSolrCell(solrId);
       }


       } catch (Exception ex) {
         //System.out.println(ex.toString());
         try
     {


          String homePath = System.getenv("HOME");
          String pathFileLog = homePath + "/.mediawhere/errors.log";
          FileOutputStream fos = new FileOutputStream(pathFileLog, true);
          PrintStream ps = new PrintStream(fos);
          Calendar cal = new GregorianCalendar();
          int giorno = cal.get(Calendar.DAY_OF_MONTH);
          int mese = cal.get(Calendar.MONTH);
          int anno = cal.get(Calendar.YEAR);
          //System.out.println(giorno + "/" + (mese + 1) + "/" + anno);
          String orario;
          int ore = cal.get(Calendar.HOUR);
          int minuti = cal.get(Calendar.MINUTE);
          int secondi = cal.get(Calendar.SECOND);

          if(cal.get(Calendar.AM_PM) == 0)
          orario = "A.M.";
          else
          orario = "P.M.";
          //System.out.println("Sono le : " + ore + ":"   + minuti + ":" + secondi + " " + orario);



          ps.println("ERROR. [" + giorno + "/" + (mese+1) + "/" + anno + "]  ["+ ore + ":"   + minuti + ":" + secondi + " " + orario +"]  Indexing file [" + path + "] failed:  " );
          ex.printStackTrace(ps);
          ps.println("\n\n");

      }
      catch (IOException e)
      {
          System.out.println("Errore: " + e);
          System.exit(1);
      }

       }
    }

    public static void indexFilesSolrCell(String pathName, String fileName, String solrId) throws IOException, SolrServerException, JpegProcessingException, MetadataException {

       String urlString = "http://localhost:8983/solr";
       SolrServer solr = new CommonsHttpSolrServer(urlString);

       try{
        File jpegFile = new File(pathName);
        Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);

        ContentStreamUpdateRequest up
         = new ContentStreamUpdateRequest("/update/extract");

       up.addFile(jpegFile);

       up.setParam("literal.id", solrId);
       up.setParam("literal.filename", fileName);
       up.setParam("uprefix", "attr_");
        // iterate through metadata directories
        Iterator directories = metadata.getDirectoryIterator();
        while (directories.hasNext()) {
        Directory directory = (Directory)directories.next();
        // iterate through tags and print to System.out
        Iterator tags = directory.getTagIterator();
        while (tags.hasNext()) {
        Tag tag = (Tag)tags.next();
        // use Tag.toString()
        System.out.println(tag);
        String tagName = tag.getTagName();
        String tmp = "";
        StringTokenizer st = new StringTokenizer(tagName, " ");//tolgo gli spazi per evitare una java.lang.illegalexception "invalid uri"
        while(st.hasMoreTokens())
        {
            tmp = tmp + st.nextToken();
        }
        
        System.out.println(tmp);
        if(tag.getDescription().length() < 64)//carico solo gli attributi che hanno un campo inferiore a 64 bit (se no--> java.io.IOException: FULL)
        up.setParam("literal."+ tmp, tag.getDescription());
        //System.out.println("Nome tag:\t"+ tag.getTagName()+"Valore tag:\t"+ tag.getDescription());

        }
        }
        up.setParam("uprefix", "attr_");
        Directory iptcDirectory = metadata.getDirectory(IptcDirectory.class);
        String caption = iptcDirectory.getString(IptcDirectory.TAG_CAPTION);
        System.out.println(caption);




       //up.setParam("fmap.content", "attr_content");

       //Sets appropriate parameters for the given ACTION
       //setAction(AbstractUpdateRequest.ACTION action,boolean waitFlush, boolean waitSearcher)
       up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);

       solr.request(up);

       QueryResponse rsp = solr.query(new SolrQuery(fileName));

       System.out.println(rsp);
    }
               catch(JpegProcessingException e){
            e.printStackTrace();

        }
     }


           public static void deleteFilesSolrCell(String solrId)
    {
        String home = System.getenv("HOME");
        System.out.println(home);
        File wd = new File(home + "/.mediawhere/found/");
        System.out.println(wd);
        Process proc = null;
        try {
           proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
        }
        catch (IOException e) {
           e.printStackTrace();
           return;
        }
        if (proc != null) {
           BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
           PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
           //out.println("cd /home/kinder/apache-solr-1.4.1/example/exampledocs/");
           out.println("java -Ddata=args -Dcommit=yes -jar post.jar " + "\"<delete><id>" + solrId + "</id></delete>\"");
           out.println("exit");
           //out.println("java -jar post.jar");
           try {
              String line;
              while ((line = in.readLine()) != null) {
                 System.out.println(line);
              }
              proc.waitFor();
              in.close();
              out.close();
              proc.destroy();
           }
           catch (Exception e) {
              e.printStackTrace();
           }
        }
    }
}

